﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace MailSender
{
    public partial class AddToAddress : Form
    {
        public  ToAddressManage ParentForm { get; set; }
        public AddToAddress()
        {
            InitializeComponent();
        }
        public AddToAddress(ToAddressManage toAdd)
        {
            InitializeComponent();
            this.ParentForm = toAdd;
        }
        private void OKBt_Click(object sender, EventArgs e)
        {
            string email = EmailTxt.Text;
            string type = TypeComboBox.SelectedItem.ToString();
            bool flag = true;
            try
            {
                XDocument doc = XDocument.Load(SysConstants.ToAddressFile);
                XElement config = doc.Element("config");
                var temp = (from server in config.Elements("toadd") where server.Attribute("type").Value == type && server.Attribute("email").Value==email select (XElement)server).SingleOrDefault();
                if (temp!=null)
                {
                    MessageBox.Show("该记录已经存在");
                    return;
                }
                else
                {
                    XElement newE = new XElement("toadd");
                    newE.Add(new XAttribute("type", type));
                    newE.Add(new XAttribute("email", email));
                    config.AddFirst(newE);
                    doc.Save(SysConstants.ToAddressFile);
                }
            }
            catch (Exception)
            {
                flag = false;
            }

            MessageBox.Show(flag==true?"添加成功":"添加失败");           
            ParentForm.LoadDataGridView();
            this.Close();
        }
    }
}
